package com.ruoyi.loginrisk.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class CurrentAddressLocator {
    private static final String API_KEY = "TUDBZ-O6O6U-HXNVE-G6FPW-UTO6S-O6FXO";

    public static String getCurrentAddress() {
        try {
            // 调用API获取IP定位信息
            String apiUrl = "https://apis.map.qq.com/ws/location/v1/ip?key=" + API_KEY;
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();

            // 解析JSON获取地址信息
            JSONObject json = new JSONObject(response.toString());
            JSONObject result = json.getJSONObject("result");
            JSONObject adInfo = result.getJSONObject("ad_info");

            // 拼接地址信息
            return adInfo.getString("city");

        } catch (Exception e) {
            e.printStackTrace();
            return "获取地址失败";
        }
    }
}